package com.lambkit.core.flow;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.File;
import java.nio.charset.Charset;

/**
 * @author yangyong(孤竹行)
 */
public class FlowInstanceJsonPathBuilder implements IFlowInstanceBuilder {

    private FlowInstanceObject flowInstanceObject;
    private String jsonPath;

    public FlowInstanceJsonPathBuilder(String jsonPath, String flowId, String flowInstanceId) {
        this.jsonPath = jsonPath;
        FlowObject flowObject = configFlowObject(flowId);
        configFlowInstanceObject(flowId, flowInstanceId, flowObject);
    }

    public FlowInstanceJsonPathBuilder(String jsonPath, FlowObject flowObject, String flowInstanceId) {
        this.jsonPath = jsonPath;
        String flowId = flowObject.getCode();
        configFlowInstanceObject(flowId, flowInstanceId, flowObject);
    }

    private FlowObject configFlowObject(String flowId) {
        FlowObject flowObject = null;
        String json = ResourceUtil.readUtf8Str(jsonPath + File.separator + flowId + ".json");
        if(StrUtil.isNotBlank(json)) {
            JSONObject jsonFlow = JSONUtil.parseObj(json);
            flowObject = jsonFlow.toBean(FlowObject.class);
        } else {
            flowObject = new FlowObject();
            flowObject.setCode(flowId);
        }
        return flowObject;
    }

    private void configFlowInstanceObject(String flowId, String flowInstanceId, FlowObject flowObject) {
        String json = ResourceUtil.readUtf8Str(jsonPath + File.separator + flowId + File.separator + flowInstanceId + ".json");
        if(StrUtil.isNotBlank(json)) {
            JSONObject jsonFlow = JSONUtil.parseObj(json);
            this.flowInstanceObject = jsonFlow.toBean(FlowInstanceObject.class);
        } else {
            this.flowInstanceObject = new FlowInstanceObject();
            this.flowInstanceObject.setFlow(flowObject);
            this.flowInstanceObject.setCode(flowInstanceId);
            this.flowInstanceObject.setTitle(flowObject.getTitle());
        }
    }

    @Override
    public FlowInstanceObject getInstance() {
        return flowInstanceObject;
    }

    @Override
    public void saveInstance() {
        if (flowInstanceObject != null) {
            String flowId = flowInstanceObject.getFlow().getCode();
            String flowInstanceId = flowInstanceObject.getCode();
            File file = new File(jsonPath + File.separator + flowId + File.separator + flowInstanceId + ".json");
            String json = JSONUtil.toJsonPrettyStr(flowInstanceObject);
            FileUtil.writeString(json, file, Charset.forName("UTF-8"));
        }
    }

}
